#include<iostream>
#include<vector>
#include<cstring>
#include<queue>

using namespace std;


typedef pair<int, int> PII;
const int N = 150010;

vector<vector<PII>> edgs;
int w[N];
int n, m;
int dist[N];
bool st[N];

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);

    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> q;
    q.push({ 0, 1 });

    while (q.size())
    {
        auto t = q.top(); q.pop();

        int ver = t.second, distance = t.first;

        if (st[ver]) continue;
        st[ver] = true;

        for (auto e : edgs[ver])
        {
            int j = e.first, val = e.second;
            if (dist[j] > dist[ver] + val)
            {
                dist[j] = dist[ver] + val;
                q.push({ dist[j], j });
            }
        }
    }

    if (dist[n] == 0x3f3f3f3f) return -1;
    else return dist[n];
}

int main()
{
    cin >> n >> m;

    edgs.resize(n + 1);

    while (m--)
    {
        int x, y, z; cin >> x >> y >> z;
        edgs[x].push_back({y, z});
    }

    cout << dijkstra();
    return 0;
}